/**
 *绑定项目设备
 */
'use strict';

const operationRecord = require("../sys/operationRecordAction");
const Transaction = require("../../libs/DB/Transaction");

module.exports = async function (params) {
    let deviceIdList = params.deviceIdList
    let transaction = new Transaction();
    try {
        await transaction.beginTransaction();
        await transaction.query('DELETE FROM project_device_mid WHERE project_id = ? AND device_type = ?',[params.projectId,params.deviceType]);

        for (const deviceId of deviceIdList) {
            let insertObj = {
                project_id:params.projectId,
                device_id:deviceId,
                device_type:params.deviceType
            }
            await transaction.query('INSERT INTO project_device_mid SET ?',[insertObj]);
        }
        await transaction.commit();
        await operationRecord(params);
        return {success: true};
    }catch (e){
        await transaction.rollback();
        return { success: false,message:e.message };
    }
};